package controller

import (
	"BlazeRider-backend/app/manager"
	"BlazeRider-backend/app/middleware"
	"BlazeRider-backend/app/models"
	"BlazeRider-backend/app/service"
	"BlazeRider-backend/app/utils"
	"BlazeRider-backend/routes"
	"fmt"
	"github.com/gin-gonic/gin"
	"net/http"
	"regexp"
	"strconv"
	"sync"
	"time"
)

type AnchorLoginRequest struct {
	Token string `json:"token"`
}

type FinishGameRequest struct {
	MsgId           string                   `json:"msg_id"`
	Champion        int                      `json:"champion"`
	FinishTrackInfo []models.FinishTrackInfo `json:"finish_track_info"`
	Timestamp       int64                    `json:"timestamp"` // 修改为 int64
}

type SetGameDataRequest struct {
	Data string `json:"data"`
}

type RecordClientErrorRequest struct {
	LiveRoomId string `json:"live_room_id"`
	Desc       string `json:"desc"`
	Env        string `json:"env"`
	ExtraS1    string `json:"extra_s_1"`
	ExtraS2    string `json:"extra_s_2"`
	ExtraS3    string `json:"extra_s_3"`
	ExtraS4    string `json:"extra_s_4"`
	ExtraS5    string `json:"extra_s_5"`
	ExtraI1    int    `json:"extra_i_1"`
	ExtraI2    int    `json:"extra_i_2"`
	ExtraI3    int    `json:"extra_i_3"`
	ExtraI4    int    `json:"extra_i_4"`
	ExtraI5    int    `json:"extra_i_5"`
}

type HttpController struct {
	mu         sync.Mutex // 添加互斥锁字段
	testSwitch int
}

func NewHttpController() *HttpController {
	return &HttpController{}
}

// controller/http_controller.go
func (h *HttpController) RegisterRoutes(router *gin.Engine) {
	apiGroup := router.Group("/api/v1")
	{
		apiGroup.GET("/users/:userId", h.GetUserInfo)
		apiGroup.POST("/user", h.CreateUser)

		// TODO 临时测试的接口
		apiGroup.POST("/testfinishGame", func(c *gin.Context) {
			fmt.Println("[DEBUG] /testfinishGame") // 测试路由是否触发
			h.finishGame(c)
		})

		//apiGroup.GET("/getPingLun", h.GetToken)
		apiGroup.POST("/getPingLun", func(c *gin.Context) {
			fmt.Println("[DEBUG] /api/v1/getPingLun hit") // 测试路由是否触发
			h.GetPingLun(c)
		})

		//apiGroup.GET("/getPingLunChuanQi", h.GetToken)
		apiGroup.POST("/getPingLunChuanQi", func(c *gin.Context) {
			fmt.Println("[DEBUG] /api/v1/getPingLunChuanQi hit") // 测试路由是否触发
			h.getPingLunChuanQi(c)
		})

		//apiGroup.GET("/getLikeRequest", h.GetToken)
		apiGroup.POST("/getLikeRequest", func(c *gin.Context) {
			fmt.Println("[DEBUG] /api/v1/getPingLun hit") // 测试路由是否触发
			h.GetLikeRequest(c)
		})

		//apiGroup.GET("/getToken", h.GetToken)
		apiGroup.POST("/getGiftRequest", func(c *gin.Context) {
			fmt.Println("[DEBUG] /api/v1/getGiftRequest hit") // 测试路由是否触发
			h.GetGiftRequest(c)
		})
		apiGroup.POST("/OpenSendManyZanRequest", func(c *gin.Context) {
			fmt.Println("[DEBUG] /api/v1/OpenSendManyZanRequest hit") // 测试路由是否触发
			h.OpenSendManyZanRequest(c)
		})

		apiGroup.POST("/OpenSendManyRequest", func(c *gin.Context) {
			fmt.Println("[DEBUG] /api/v1/OpenSendManyRequest hit") // 测试路由是否触发
			h.OpenSendManyRequest(c)
		})

		apiGroup.POST("/CloseSendManyRequest", func(c *gin.Context) {
			fmt.Println("[DEBUG] /api/v1/CloseSendManyRequest hit") // 测试路由是否触发
			h.CloseSendManyRequest(c)
		})

		//apiGroup.GET("/getToken", h.GetToken)
		apiGroup.POST("/auth/anchor/login", func(c *gin.Context) {
			fmt.Println("[DEBUG] /auth/anchor/login hit") // 测试路由是否触发
			h.AuthAnchorLogin(c)
		})

		//apiGroup.GET("/getToken", h.GetToken)
		apiGroup.POST("/testDyToken", func(c *gin.Context) {
			fmt.Println("[DEBUG] /GetToken hit") // 测试路由是否触发
			h.TestDyToken(c)
		})

		apiGroup.GET("/testFailGiftRecord", func(c *gin.Context) {
			fmt.Println("[DEBUG] /testFailGiftRecord") // 测试路由是否触发
			h.testFailGiftRecord(c)
		})

		apiGroup.POST("/recordClientError", func(c *gin.Context) {
			fmt.Println("[DEBUG] /recordClientError") // 测试路由是否触发
			h.recordClientError(c)
		})

		//apiGroup.GET("/getToken", h.GetToken)
		// 需要验证 Token 的路由
		authGroup := apiGroup.Group("/auth")
		authGroup.Use(middleware.LiveRoomAuthMiddleware())
		{
			authGroup.POST("/finishGame", func(c *gin.Context) {
				fmt.Println("[DEBUG] /finishGame") // 测试路由是否触发
				h.finishGame(c)
			})

			authGroup.GET("/getRanks", func(c *gin.Context) {
				fmt.Println("[DEBUG] /getRanks") // 测试路由是否触发
				h.getRanks(c)
			})

			authGroup.GET("/getWorldRecords", func(c *gin.Context) {
				fmt.Println("[DEBUG] /getWorldRecords") // 测试路由是否触发
				h.getWorldRecords(c)
			})

			authGroup.POST("/setGameData", func(c *gin.Context) {
				fmt.Println("[DEBUG] /setGameData") // 测试路由是否触发
				h.setGameData(c)
			})

			authGroup.POST("/getGameData", func(c *gin.Context) {
				fmt.Println("[DEBUG] /getGameData") // 测试路由是否触发
				h.getGameData(c)
			})
		}

	}
}

// 示例：获取用户信息的HTTP处理
func (h *HttpController) GetUserInfo(c *gin.Context) {
	userID := c.Param("userId")

	user, error := manager.Get().UserManager().GetUser(userID)
	if error != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "User not found"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"user_id":  user.UserID,
		"username": user.UserName,
		"avatar":   user.HeadImg,
		"level":    user.Level,
		"score":    user.Score,
	})
}

// 示例：获取用户信息的HTTP处理
func (h *HttpController) AuthAnchorLogin(c *gin.Context) {
	var req AnchorLoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request format"})
		return
	}

	if req.Token == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no token"})
		return
	}

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data": gin.H{
			"token": req.Token,
		},
	})
}

// 发送批量请求开启
func (h *HttpController) OpenSendManyZanRequest(c *gin.Context) {
	var req models.GiftRequestPayloadArr
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request format"})
		return
	}

	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	go h.SendManyZanRequest(roomId)

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    gin.H{},
	})
}

// 发送批量请求
func (h *HttpController) SendManyZanRequest(liveRoomID string) {

	if h.testSwitch == 1 {
		return
	}

	h.testSwitch = 1

	// 定义 User 结构体
	type User struct {
		Username    string
		UserId      string
		UserImgHead string
	}

	// 初始化 User 数组（包含 3 个元素）
	users := [3]User{
		{Username: "Alice", UserId: "1001", UserImgHead: "http://82.157.179.66:8001/static/03763e7c5fd77d3ba9d0ed2b35f5bfeb.jpeg"},
		{Username: "Bob", UserId: "1002", UserImgHead: "http://82.157.179.66:8001/static/16e1041e5e02db1c77678084102a9b6b.jpeg"},
		{Username: "Charlie", UserId: "1003", UserImgHead: "http://82.157.179.66:8001/static/8944face68cc71bc452ea8a4fd0abc5b.jpeg"},
	}

	for i := 0; i < len(users); i++ {
		service.LiveRoomService{}.SendTestPingLunNoStoage(liveRoomID, users[i].UserId, users[i].Username, users[i].UserImgHead, i+1)
	}

	// 初始化礼物 ID 字符串数组（包含 5 个元素）
	giftIds := [1]string{
		"1",
	}

	accScore := 0
	for {
		if h.testSwitch == 0 {
			break
		}

		for i := 0; i < len(users); i++ {
			for j := 0; j < len(giftIds); j++ {
				accScore++
				service.LiveRoomService{}.SendTestGiftNoStoage(liveRoomID, users[i].UserId, users[i].Username, users[i].UserImgHead,
					giftIds[j], 1, i+1, accScore)

				time.Sleep(10 * time.Millisecond)
			}
		}
	}

	return
}

// 发送批量请求开启
func (h *HttpController) OpenSendManyRequest(c *gin.Context) {
	var req models.GiftRequestPayloadArr
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request format"})
		return
	}

	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	go h.SendManyRequest(roomId)

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    gin.H{},
	})
}

// 发送批量请求
func (h *HttpController) SendManyRequest(liveRoomID string) {

	if h.testSwitch == 1 {
		return
	}

	h.testSwitch = 1

	// 定义 User 结构体
	type User struct {
		Username    string
		UserId      string
		UserImgHead string
	}

	// 初始化 User 数组（包含 3 个元素）
	users := [3]User{
		{Username: "Alice", UserId: "1001", UserImgHead: "http://82.157.179.66:8001/static/03763e7c5fd77d3ba9d0ed2b35f5bfeb.jpeg"},
		{Username: "Bob", UserId: "1002", UserImgHead: "http://82.157.179.66:8001/static/16e1041e5e02db1c77678084102a9b6b.jpeg"},
		{Username: "Charlie", UserId: "1003", UserImgHead: "http://82.157.179.66:8001/static/8944face68cc71bc452ea8a4fd0abc5b.jpeg"},
	}

	for i := 0; i < len(users); i++ {
		service.LiveRoomService{}.SendTestPingLunNoStoage(liveRoomID, users[i].UserId, users[i].Username, users[i].UserImgHead, i+1)
	}

	// 初始化礼物 ID 字符串数组（包含 5 个元素）
	giftIds := [9]string{
		"1",
		"n1/Dg1905sj1FyoBlQBvmbaDZFBNaKuKZH6zxHkv8Lg5x2cRfrKUTb8gzMs=",
		"28rYzVFNyXEXFC8HI+f/WG+I7a6lfl3OyZZjUS+CVuwCgYZrPrUdytGHu0c=",
		"fJs8HKQ0xlPRixn8JAUiL2gFRiLD9S6IFCFdvZODSnhyo9YN8q7xUuVVyZI=",
		"PJ0FFeaDzXUreuUBZH6Hs+b56Jh0tQjrq0bIrrlZmv13GSAL9Q1hf59fjGk=",
		"IkkadLfz7O/a5UR45p/OOCCG6ewAWVbsuzR/Z+v1v76CBU+mTG/wPjqdpfg=",
		"gx7pmjQfhBaDOG2XkWI2peZ66YFWkCWRjZXpTqb23O/epru+sxWyTV/3Ufs=",
		"pGLo7HKNk1i4djkicmJXf6iWEyd+pfPBjbsHmd3WcX0Ierm2UdnRR7UINvI=",
		"P7zDZzpeO215SpUptB+aURb1+zC14UC9MY1+MHszKoF0p5gzYk8CNEbey60=",
	}

	accScore := 0
	for {
		if h.testSwitch == 0 {
			break
		}
		for i := 0; i < len(users); i++ {
			for j := 0; j < len(giftIds); j++ {

				giftInfo, err := manager.Get().GiftManager().GetGiftByID(giftIds[j])
				if err != nil {
				}

				giftScore := giftInfo.Score
				accScore = accScore + giftScore
				service.LiveRoomService{}.SendTestGiftNoStoage(liveRoomID, users[i].UserId, users[i].Username, users[i].UserImgHead,
					giftIds[j], 1, i+1, accScore)

				time.Sleep(10 * time.Millisecond)
			}
		}
	}

	return
}

// 发送批量请求关闭
func (h *HttpController) CloseSendManyRequest(c *gin.Context) {
	var req models.GiftRequestPayloadArr
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request format"})
		return
	}

	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	h.testSwitch = 0

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    gin.H{},
	})

}

// 示例：获取用户信息的HTTP处理
func (h *HttpController) finishGame(c *gin.Context) {
	var req FinishGameRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request format"})
		return
	}

	if req.MsgId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no msg_id"})
		return
	}

	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	res, err := service.LiveRoomService{}.FinishGame(req.MsgId, roomId, req.FinishTrackInfo, int(req.Timestamp))
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		//return
	}

	if roomId != utils.TestRoomId {
		err := service.DouYinService{}.StopDouYinLiveRoomAllTask(roomId)
		if err != nil {
			fmt.Println("stop dou yin live room all task err : ", err, ", room id : ", roomId)
		}

		err = service.DouYinService{}.SyncGameStatusToDouYinService(roomId, 2, req.FinishTrackInfo)
		if err != nil {
			fmt.Println("sync game status end to dou yin err : ", err, ", room id : ", roomId)
		}
	}

	go service.DouYinService{}.DealUploadUserGameResultService(roomId)

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data": gin.H{
			"result": res,
		},
	})
}

// 示例：获取用户信息的HTTP处理
func (h *HttpController) getRanks(c *gin.Context) {
	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	res, err := manager.Get().UserManager().GetRanks()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data": gin.H{
			"ranks": res,
		},
	})
}

// 示例：获取用户信息的HTTP处理
func (h *HttpController) getWorldRecords(c *gin.Context) {
	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	res, err := manager.Get().UserManager().GetWorldRecords()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data": gin.H{
			"records": res,
		},
	})
}

// 示例：获取用户信息的HTTP处理
func (h *HttpController) setGameData(c *gin.Context) {
	var req SetGameDataRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request format"})
		return
	}

	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	liveRoomInfo, err := manager.Get().LiveRoomManager().GetLiveInfo(roomId)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	err = manager.Get().LiveRoomManager().SetGameData(roomId, liveRoomInfo.Times, req.Data)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    gin.H{},
	})
}

// 示例：获取用户信息的HTTP处理
func (h *HttpController) getGameData(c *gin.Context) {
	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":     "no roomid",
			"errorCode": 10403,
		})
		return
	}

	liveRoomInfo, err := manager.Get().LiveRoomManager().GetLiveInfo(roomId)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":     err.Error(),
			"errorCode": 10404,
		})
		return
	}

	if liveRoomInfo.State == "end" {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":     "game not start",
			"errorCode": 10101,
		})
		return
	}

	gameData, err := manager.Get().LiveRoomManager().GetGameData(roomId, liveRoomInfo.Times)
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error":     err.Error(),
			"errorCode": 500,
		})
		return
	}

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data": gin.H{
			"gameData": gameData,
		},
	})
}

// 示例：获取用户信息的HTTP处理
func (h *HttpController) testFailGiftRecord(c *gin.Context) {
	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	err := service.DouYinService{}.DealDouYinAllGiftFailedData()
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    gin.H{},
	})
}

// 记录客户端错误
func (h *HttpController) recordClientError(c *gin.Context) {

	fmt.Println("\n接收到客户端错误记录请求：\n")

	// 处理参数
	var req RecordClientErrorRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		fmt.Println("\n接收到客户端错误记录请求 invalid  format：" + err.Error() + "\n")
		c.JSON(http.StatusBadRequest, gin.H{
			"error": "invalid request format: " + err.Error(), // 将具体错误信息附加到响应
		})
		return
	}

	fmt.Println("\n接收到客户端错误记录请求 here222：\n")
	err := manager.Get().ClientErrorRecordManager().AddClientErrorRecord(req.LiveRoomId, req.Desc, req.Env,
		req.ExtraS1, req.ExtraS2, req.ExtraS3, req.ExtraS4, req.ExtraS5,
		req.ExtraI1, req.ExtraI2, req.ExtraI3, req.ExtraI4, req.ExtraI5)
	if err != nil {
		fmt.Println("\n接收到客户端错误记录请求 here333：\n")
		c.JSON(http.StatusBadRequest, gin.H{
			"error": err.Error(),
		})
		return
	}

	fmt.Println("\n成功记录数据：", req.LiveRoomId, req.Desc, req.Env,
		req.ExtraS1, req.ExtraS2, req.ExtraS3, req.ExtraS4, req.ExtraS5,
		req.ExtraI1, req.ExtraI2, req.ExtraI3, req.ExtraI4, req.ExtraI5, "\n")

	alarmTxt := fmt.Sprintf("客户端错误上报：直播间ID: %s, 错误内容: %s, 环境： %s, 扩展字段1: %s, 扩展字段2: %s, 扩展字段3: %s, 扩展字段4: %s, 扩展字段5: %s, 扩展数字1: %d, 扩展数字2: %d, 扩展数字3: %d, 扩展数字4: %d, 扩展数字5: %d",
		req.LiveRoomId, req.Desc, req.Env,
		req.ExtraS1, req.ExtraS2, req.ExtraS3, req.ExtraS4, req.ExtraS5,
		req.ExtraI1, req.ExtraI2, req.ExtraI3, req.ExtraI4, req.ExtraI5,
	)

	go utils.FeiShuAlarm(alarmTxt)

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    gin.H{},
	})
}

// 示例：获取用户信息的HTTP处理
func (h *HttpController) GetPingLun(c *gin.Context) {
	var req models.CommentRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request format"})
		return
	}

	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	// 初始化 转换用户信息
	userInfos := make([]manager.UserInfo, 0, len(req.Arr))
	for _, item := range req.Arr {
		// 尝试获取已存在的用户信息
		//existingUser, err := manager.Get().UserManager().GetUser(item.SecOpenID)
		//if err != nil {
		// 用户不存在时进行初始化（示例值）
		if err := manager.Get().UserManager().InitializeUser(
			item.SecOpenID,
			item.Nickname,
			item.AvatarURL,
			1, // 初始等级
		); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "user initialization failed"})
			return
		}
		existingUser, _ := manager.Get().UserManager().GetUser(item.SecOpenID)
		//}

		userInfos = append(userInfos, manager.UserInfo{
			UserID:   existingUser.UserID,
			UserName: existingUser.UserName,
			HeadImg:  existingUser.HeadImg,
			Level:    existingUser.Level,
			Rank:     existingUser.Rank,
			Score:    existingUser.Score,
		})
	}

	/* 处理评论数据 */
	// 筛选出加入赛道的数据
	joinMatchStrArray := []string{"1", "2", "3"}

	// 用于存储最终筛选结果（保留最早时间的评论）
	// 定义一个新的切片，保持和原始结构相同的结构
	var finalComments []struct {
		MsgID     string `json:"msg_id"`
		SecOpenID string `json:"sec_openid"`
		Content   string `json:"content"`
		AvatarURL string `json:"avatar_url"`
		Nickname  string `json:"nickname"`
		Timestamp int64  `json:"timestamp"`
	}

	// 用于记录每个 SecOpenID 的最早评论
	secOpenIDMap := make(map[string]struct {
		MsgID     string
		SecOpenID string
		Content   string
		AvatarURL string
		Nickname  string
		Timestamp int64
	})

	// 遍历 req.Arr，筛选符合条件的评论
	for _, item := range req.Arr {
		// 检查 Content 是否在 matchStrArray 中
		for _, matchStr := range joinMatchStrArray {
			if item.Content == matchStr {
				// 检查是否已经存在该 SecOpenID 的评论
				if existingItem, exists := secOpenIDMap[item.SecOpenID]; !exists || item.Timestamp < existingItem.Timestamp {
					// 如果不存在，或者当前评论的时间更早，则更新记录
					secOpenIDMap[item.SecOpenID] = struct {
						MsgID     string
						SecOpenID string
						Content   string
						AvatarURL string
						Nickname  string
						Timestamp int64
					}(item)
				}
				break
			}
		}
	}

	// 将 map 中的值转换为切片
	for _, item := range secOpenIDMap {
		finalComments = append(finalComments, struct {
			MsgID     string `json:"msg_id"`
			SecOpenID string `json:"sec_openid"`
			Content   string `json:"content"`
			AvatarURL string `json:"avatar_url"`
			Nickname  string `json:"nickname"`
			Timestamp int64  `json:"timestamp"`
		}{
			MsgID:     item.MsgID,
			SecOpenID: item.SecOpenID,
			Content:   item.Content,
			AvatarURL: item.AvatarURL,
			Nickname:  item.Nickname,
			Timestamp: item.Timestamp,
		})
	}

	for _, item := range finalComments {
		track, _ := strconv.Atoi(item.Content)
		service.LiveRoomService{}.OneUserJoinTrack(roomId, item.SecOpenID, item.Nickname, item.AvatarURL, track, 0)

	}

	// 处理除加入外的互动
	actRegexArray := []*regexp.Regexp{
		regexp.MustCompile(`^6+$`), // 匹配任意长度的全6字符串（如"6", "666"），代表加油
	}

	// finalComments = finalComments[:0] 后，切片可继续存储的元素数量​​上限为原容量值​​，超出时会按 Go 的规则自动扩容（无固定限制，但受内存约束）。复用切片时，此操作是​​高性能最佳实践
	finalComments = finalComments[:0]

	var actMsgList []struct {
		MsgID     string `json:"msg_id"`
		SecOpenID string `json:"sec_openid"`
		Content   string `json:"content"`
		AvatarURL string `json:"avatar_url"`
		Nickname  string `json:"nickname"`
		Timestamp int64  `json:"timestamp"`
	}

	// 遍历 req.Arr，筛选符合条件的评论
	for _, item := range req.Arr {
		// 检查 Content 是否在 matchStrArray 中
		for _, reg := range actRegexArray {
			if reg.MatchString(item.Content) {
				// 检查是否已经存在该 SecOpenID 的评论
				actMsgList = append(actMsgList, struct {
					MsgID     string `json:"msg_id"`
					SecOpenID string `json:"sec_openid"`
					Content   string `json:"content"`
					AvatarURL string `json:"avatar_url"`
					Nickname  string `json:"nickname"`
					Timestamp int64  `json:"timestamp"`
				}{
					MsgID:     item.MsgID,
					SecOpenID: item.SecOpenID,
					Content:   item.Content,
					AvatarURL: item.AvatarURL,
					Nickname:  item.Nickname,
					Timestamp: item.Timestamp,
				})
				break
			}
		}
	}

	// 处理非加入轨道类互动评论
	for _, item := range actMsgList {
		if actRegexArray[0].MatchString(item.Content) {
			if err := manager.Get().UserManager().InitializeUser(
				item.SecOpenID,
				item.Nickname,
				item.AvatarURL,
				1, // 初始等级
			); err != nil {

			}
			// 匹配并赠送666字符串的加速
			err := service.LiveRoomService{}.OneUserSendGift(item.MsgID, roomId, item.SecOpenID, "4", 1)
			if err != nil {
			}
		}
	}

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data": gin.H{
			"userInfos":     userInfos,
			"finalComments": finalComments,
		},
	})
}

// 示例：获取用户信息的HTTP处理
func (h *HttpController) getPingLunChuanQi(c *gin.Context) {
	var req models.CommentRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request format"})
		return
	}

	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	// 初始化 转换用户信息
	userInfos := make([]manager.UserInfo, 0, len(req.Arr))
	for _, item := range req.Arr {
		// 尝试获取已存在的用户信息
		//existingUser, err := manager.Get().UserManager().GetUser(item.SecOpenID)
		//if err != nil {
		// 用户不存在时进行初始化（示例值）
		if err := manager.Get().UserManager().InitializeUser(
			item.SecOpenID,
			item.Nickname,
			item.AvatarURL,
			1, // 初始等级
		); err != nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "user initialization failed"})
			return
		}
		existingUser, _ := manager.Get().UserManager().GetUser(item.SecOpenID)
		//}

		userInfos = append(userInfos, manager.UserInfo{
			UserID:   existingUser.UserID,
			UserName: existingUser.UserName,
			HeadImg:  existingUser.HeadImg,
			Level:    existingUser.Level,
			Rank:     existingUser.Rank,
			Score:    existingUser.Score,
		})
	}

	// 筛选出加入赛道的数据

	// 用于存储最终筛选结果（保留最早时间的评论）
	// 定义一个新的切片，保持和原始结构相同的结构
	var finalComments []struct {
		MsgID     string `json:"msg_id"`
		SecOpenID string `json:"sec_openid"`
		Content   string `json:"content"`
		AvatarURL string `json:"avatar_url"`
		Nickname  string `json:"nickname"`
		Timestamp int64  `json:"timestamp"`
	}

	// 用于记录每个 SecOpenID 的最早评论
	secOpenIDMap := make(map[string]struct {
		MsgID     string
		SecOpenID string
		Content   string
		AvatarURL string
		Nickname  string
		Timestamp int64
	})

	// 遍历 req.Arr，筛选符合条件的评论
	for _, item := range req.Arr {
		// 检查 Content 是否在 matchStrArray 中
		//for _, matchStr := range matchStrArray {
		//	if item.Content == matchStr {
		// 检查是否已经存在该 SecOpenID 的评论
		if utils.CheckChuanQiPingLun(item.Content) {
			if existingItem, exists := secOpenIDMap[item.SecOpenID]; !exists || item.Timestamp < existingItem.Timestamp {
				// 如果不存在，或者当前评论的时间更早，则更新记录
				secOpenIDMap[item.SecOpenID] = struct {
					MsgID     string
					SecOpenID string
					Content   string
					AvatarURL string
					Nickname  string
					Timestamp int64
				}(item)
			}
		}

		break
		//	}
		//}
	}

	// 将 map 中的值转换为切片
	for _, item := range secOpenIDMap {
		finalComments = append(finalComments, struct {
			MsgID     string `json:"msg_id"`
			SecOpenID string `json:"sec_openid"`
			Content   string `json:"content"`
			AvatarURL string `json:"avatar_url"`
			Nickname  string `json:"nickname"`
			Timestamp int64  `json:"timestamp"`
		}{
			MsgID:     item.MsgID,
			SecOpenID: item.SecOpenID,
			Content:   item.Content,
			AvatarURL: item.AvatarURL,
			Nickname:  item.Nickname,
			Timestamp: item.Timestamp,
		})
	}

	for _, item := range finalComments {
		track, job, err := utils.FormatSplitChuanQiPingLun(item.Content)
		if err != nil {
			continue
		}
		service.LiveRoomService{}.OneUserJoinTrack(roomId, item.SecOpenID, item.Nickname, item.AvatarURL, track, job)

	}

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data": gin.H{
			"userInfos":     userInfos,
			"finalComments": finalComments,
		},
	})
}

// 示例：获取用户信息的HTTP处理
func (h *HttpController) GetLikeRequest(c *gin.Context) {
	var req models.LikeRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request format"})
		return
	}

	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	for _, item := range req.Arr {
		if err := manager.Get().UserManager().InitializeUser(
			item.SecOpenID,
			item.Nickname,
			item.AvatarURL,
			1, // 初始等级
		); err != nil {

		}
		err := service.LiveRoomService{}.OneUserSendGift(item.MsgID, roomId, item.SecOpenID,
			"1", item.LikeNum)
		if err != nil {
		}

	}

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    gin.H{},
	})
}

// 示例：获取用户信息的HTTP处理
func (h *HttpController) GetGiftRequest(c *gin.Context) {
	var req models.GiftRequestPayloadArr
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request format"})
		return
	}

	// 检查 x-roomid 的值
	roomId := c.GetHeader("x-roomid")
	if roomId == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "no roomid"})
		return
	}

	for _, item := range req.Arr {
		if err := manager.Get().UserManager().InitializeUser(
			item.SecOpenID,
			item.Nickname,
			item.AvatarURL,
			1, // 初始等级
		); err != nil {

		}
		err := service.LiveRoomService{}.OneUserSendGift(item.MsgID, roomId, item.SecOpenID,
			item.SecGiftId, item.GiftNum)
		if err != nil {
			fmt.Println("error: can not send gift error :", err, ", room id : ", roomId)
		}

	}

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data":    gin.H{},
	})
}

// 处理POST请求示例
func (h *HttpController) CreateUser(c *gin.Context) {
	type CreateUserRequest struct {
		Username string `json:"username" binding:"required"`
		Avatar   string `json:"avatar"`
	}

	var req CreateUserRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 生成用户ID等业务逻辑
	// ...

	c.JSON(http.StatusCreated, gin.H{
		"user_id":  "generated_id",
		"username": req.Username,
	})
}

// 示例：获取用户信息的HTTP处理
func (h *HttpController) TestDyToken(c *gin.Context) {
	token, err := service.DouYinService{}.GetToken()
	if err != nil {
		fmt.Printf("manager get token error : %v", err)
	}

	// 返回处理结果（根据业务需求调整返回结构）
	c.JSON(http.StatusOK, gin.H{
		"code":    0,
		"message": "success",
		"data": gin.H{
			"token": token,
		},
	})
}

func (hc *HttpController) StartTicker() {
	ticker := time.NewTicker(5000 * time.Millisecond) // 调整 ticker 间隔为更合理的值
	quit := make(chan struct{})

	go func() {
		for {
			select {
			case <-ticker.C:
				hc.mu.Lock() // 确保在遍历和修改 conns 时不会发生并发问题
				//fmt.Println("ticker DealDouYinAllGiftFailedData start")
				err := service.DouYinService{}.DealDouYinAllGiftFailedData()
				if err != nil {
					fmt.Println("ticker DealDouYinAllGiftFailedData err : ", err)
				}
				hc.mu.Unlock()
			case <-quit:
				ticker.Stop()
				return
			}
		}
	}()
}

// 在http_controller.go文件底部添加
var _ routes.Registrar = (*HttpController)(nil) // 接口实现检查
